package org.bookie.model.hibernate;

import java.util.List;

import org.bookie.model.Account;
import org.bookie.model.BetSlip;
import org.bookie.model.Transaction;
import org.bookie.model.User;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.event.PostLoadEvent;
import org.hibernate.event.PostLoadEventListener;

public class UserPostLoadEventListener implements PostLoadEventListener {
	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("unchecked")
	public void onPostLoad(PostLoadEvent event) {
		Object entity = event.getEntity();
		if(!entity.getClass().equals(User.class)){
			return;
		}

		Double sum =(Double) event.getSession()
					.createCriteria(Transaction.class)
						.setProjection(Projections.sum("amount"))
						.add(Restrictions.eq("user.id", event.getId()))
						.uniqueResult();
		User user = (User)entity;
		user.getAccount().setBalance(sum);
		
		List<Transaction> list = event.getSession().createCriteria(Transaction.class)
				.add(Restrictions.eq("user.id", event.getId())).list();
		double balance = Account.REFILL_AMOUNT.doubleValue();
		for(Transaction trx:list){
			BetSlip bs = trx.getBetSlip();
			if(bs!=null && bs.isClosed()){
				balance+=trx.getAmount().doubleValue();
			}
		}
		user.getAccount().setBetSlipBalance(balance);
	}

}
